package com.asgard.utils;

import org.bouncycastle.asn1.ASN1ObjectIdentifier;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DEROctetString;
import org.bouncycastle.asn1.x509.DisplayText;

import java.io.IOException;
import java.security.cert.X509Certificate;

public class ExtensionUtils {

    public static final ASN1ObjectIdentifier ROLE = new ASN1ObjectIdentifier("1.2.6.1").intern();
    public static final ASN1ObjectIdentifier SUB_ROLE = new ASN1ObjectIdentifier("1.2.6.2").intern();
    public static final ASN1ObjectIdentifier MEMBER_ID = new ASN1ObjectIdentifier("1.2.6.3").intern();
    public static final ASN1ObjectIdentifier ISSURE_SN = new ASN1ObjectIdentifier("1.2.6.4").intern();
    public static final ASN1ObjectIdentifier ISSURE_MEMBER_ID = new ASN1ObjectIdentifier("1.2.6.5").intern();

    /**
     * 解析证书中的字符串。
     *
     * @param oid  证书OID
     * @param cert 证书
     * @return 证书中的字符串
     */
    public static String parseDisplayText(ASN1ObjectIdentifier oid, X509Certificate cert) {
        byte[] bytes = cert.getExtensionValue(oid.getId());
        return parseDisplayText(bytes);
    }

    /**
     * 解析证书中的字符串。
     *
     * @param bytes 字节数组
     * @return 证书中的字符串
     */
    public static String parseDisplayText(byte[] bytes) {
        DisplayText displayText;
        try {
            ASN1OctetString dd = DEROctetString.getInstance(ASN1Primitive.fromByteArray(bytes));
            displayText = DisplayText.getInstance(ASN1Primitive.fromByteArray(dd.getOctets()));
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return displayText.getString();
    }

}

